package com.gin.no_gay_alliance.fragment.post.attach;

import static com.gin.no_gay_alliance.adpter.AttachmentItemAdapter.findUrl;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.method.NukeApi;
import com.gin.nga.params.nuke.DelAttachParam;
import com.gin.nga.response.field.Attachment;
import com.gin.nga.response.post.PrepareBody;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.adpter.AttachmentItemAdapter;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.RequestCallback;
import com.gin.no_gay_alliance.databinding.FragmentUploadedBinding;
import com.gin.no_gay_alliance.databinding.ItemUploadBodyBinding;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.itemdecoration.SimpleItemDecoration;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.HandlerMessage;
import com.gin.no_gay_alliance.utils.ImageUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.AttachmentModel;
import com.gin.no_gay_alliance.viewmodel.InsertText;

import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 已上传附件
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/29 22:50
 **/

public class UploadedFragment extends BaseBindingFragment<FragmentUploadedBinding> implements View.OnClickListener {
    private BaseBindingRecyclerViewAdapter<ItemUploadBodyBinding, AttachmentModel> adapter;
    private Args args;

    @Override
    protected void onCreateView() {
        if (getArguments() != null) {
            this.args = getArguments().getParcelable(Args.class.getName());
        } else {
            throw new RequireParamException();
        }
        adapter = new BaseBindingRecyclerViewAdapter<ItemUploadBodyBinding, AttachmentModel>(requireActivity(), args.attachments) {
            @Override
            protected void onBindViewHolder(ViewHolder<ItemUploadBodyBinding> holder,
                                            @NonNull ItemUploadBodyBinding b,
                                            int position,
                                            AttachmentModel item) {
                ImageView iv = b.iv;
                TextView tv = b.tv;
                tv.setText("删除");
                ViewUtils.setTag(item, iv, tv);
                ViewUtils.setOnClickListener(UploadedFragment.this, iv, tv);

                AttachmentItemAdapter.configAttachmentThumb(item.extension, iv,
                        i -> ImageUtils.loadAttachment(context, Attachment.PREFIX + findUrl(item), i));
            }

            @NonNull
            @Override
            protected ItemUploadBodyBinding buildBinding(LayoutInflater inflater) {
                return ItemUploadBodyBinding.inflate(inflater);
            }
        };
        b.recyclerView.setAdapter(adapter);
        b.recyclerView.addItemDecoration(new SimpleItemDecoration());
    }


    /**
     * grid中的item的点击事件
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        AttachmentModel item = (AttachmentModel) v.getTag();
        int index = args.attachments.indexOf(item);
        if (v.getId() == R.id.tv) {
            // 删除
            AlertDialogUtils.showConfirm(requireContext(), "删除附件", "即将删除已上传的附件", (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    DelAttachParam param = new DelAttachParam(args.topicId, args.replyId, item.filename);
                    NukeApi.attachDel(MyApplication.getClient(), param).async(new RequestCallback<>(data -> {
                        toast(data.getMessage());
                        args.attachments.remove(index);
                        ui(() -> adapter.notifyItemRemoved(index));
                    }));
                }
            });
        }
        if (v.getId() == R.id.iv) {
            // 插入代码

            // 图片
            if ("zip".equals(item.extension)) {
                // 压缩包
                sendInsertMessage(String.format("[url=%s%s]下载文件: %s[/url]"
                        , Attachment.PREFIX
                        , item.url
                        , item.getDisplayName()
                ));
            } else if ("mp3".equals(item.extension) || "mp4".equals(item.extension)) {
                // 音视频
                sendInsertMessage(String.format("[flash]./%s[/flash]", item.url));
            } else {
                // 图片
                String url;
                if (!ObjectUtils.isEmpty(item.thumbUrls)) {
                    // 优先选择缩略图
                    url = item.thumbUrls.get(item.thumbUrls.size() - 1);
                } else {
                    // 原图
                    url = item.url;
                }
                String code = String.format("[img]./%s[/img]", url);
                sendInsertMessage(code);
            }

            // todo 长按预览或其他操作


        }
    }

    /**
     * 发送插入消息
     */
    private void sendInsertMessage(String start) {
        getParentHandler().sendMessage(getParentHandler().obtainMessage(HandlerMessage.INSERT_TEXT, new InsertText(start, null)));
    }

    public static UploadedFragment newInstance(Args args) {
        UploadedFragment fragment = new UploadedFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Args.class.getName(), args);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static class Args implements Parcelable {
        public static final Creator<Args> CREATOR = new Creator<Args>() {
            @Override
            public Args createFromParcel(Parcel in) {
                return new Args(in);
            }

            @Override
            public Args[] newArray(int size) {
                return new Args[size];
            }
        };
        public ArrayList<AttachmentModel> attachments;
        public Long topicId;
        public Long replyId;

        public Args(ArrayList<AttachmentModel> attachments, Long topicId, Long replyId) {
            this.attachments = attachments;
            this.topicId = topicId;
            this.replyId = replyId;
        }

        public Args(PrepareBody body) {
            this.topicId = body.getTopicId();
            this.replyId = body.getReplyId();
            if (body.getAttachments() != null) {
                this.attachments = body.getAttachments()
                        .values()
                        .stream()
                        .map(AttachmentModel::new)
                        .collect(Collectors.toCollection(ArrayList::new));
            } else {
                this.attachments = new ArrayList<>();
            }
        }

        protected Args(Parcel in) {
            attachments = in.createTypedArrayList(AttachmentModel.CREATOR);
            if (in.readByte() == 0) {
                topicId = null;
            } else {
                topicId = in.readLong();
            }
            if (in.readByte() == 0) {
                replyId = null;
            } else {
                replyId = in.readLong();
            }
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeTypedList(attachments);
            if (topicId == null) {
                dest.writeByte((byte) 0);
            } else {
                dest.writeByte((byte) 1);
                dest.writeLong(topicId);
            }
            if (replyId == null) {
                dest.writeByte((byte) 0);
            } else {
                dest.writeByte((byte) 1);
                dest.writeLong(replyId);
            }
        }
    }
}